package com.bawei.module_home.ui

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.base.BaseResponse
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.module_home.data.HomeItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val repository: HomeRepository
):BaseViewModel(){
    var currentCategoryId: Int = 0
    // 使用单一状态流管理数据
    private val _homeState = MutableStateFlow<RequestEvent>(Loading)
    val homeState = _homeState.asStateFlow()

    // 暴露数据列表
    val homeList = MutableStateFlow<List<HomeItem>?>(null)

    fun searchHomeById(id: Int) {
        currentCategoryId = id
        viewModelScope.launch {
            _homeState.value = Loading // 显示加载状态

            try {
                val result = repository.getHomeListById(id)
                result.onSuccess { dataList ->
                    Log.d("HomeViewModel", "数据: $dataList")

                    // 更新数据列表和状态
                    homeList.value = dataList
                    _homeState.value = Success
                }.onFailure { e ->
                    _homeState.value = Failed(e.message ?: "请求失败")
                }
            } catch (e: Exception) {
                _homeState.value = Failed(e.message ?: "未知错误")
            }
        }
    }
}